package com.example.qcweb;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.dao.UserService;
import com.example.qc.R;

import org.apache.http.util.EncodingUtils;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class LoginActivity extends Activity {
    EditText username;
    EditText password;
    Button login, register, cancel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        //无标题栏
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        //全屏模式
        //getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        //setContentView(R.layout.)
        SharedPreferences sharedPreferences = this.getSharedPreferences("share", MODE_PRIVATE);
        boolean isFirstRun = sharedPreferences.getBoolean("isFirstRun", true);
        Editor editor = sharedPreferences.edit();
        if (isFirstRun) {
            DirManager.createProjectDir();//创建文件路径
            upgradeRootPermission(getPackageName());//设置文件权限
            CreateUserFile();
            DataManager.InitTables(LoginActivity.this);
            DataManager.InitUser(LoginActivity.this);
            editor.putBoolean("isFirstRun", false);
            editor.commit();
        }

        // DataManager.InitUser(LoginActivity.this);
        findViews();
    }


    private void CreateUserFile() {
        // TODO Auto-generated method stub

        // TODO Auto-generated method stub
        String userpathString = DirManager.getXmlUserPath();

        //从asset中获取文件
        String fileName = "user.xml"; //文件名字
        String res = "";

        try {
            InputStream in = getResources().getAssets().open(fileName);
            int length = in.available();

            byte[] buffer = new byte[length];

            in.read(buffer);

            res = EncodingUtils.getString(buffer, "UTF-8");

        } catch (Exception e) {

            e.printStackTrace();

        }

        File file = new File(userpathString + "/user.xml");
        try {
            FileOutputStream fout = new FileOutputStream(file);
            try {
                fout.write(res.getBytes());
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                fout.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    }


    private void upgradeRootPermission(String packagename) {
        // TODO Auto-generated method stub
        Process process = null;
        DataOutputStream oStream = null;
        String cmddata = " chmod 777 /data";
        String cmddatadata = " chmod 777 /data/data";
        String cmd = cmddatadata + "/" + packagename;
        String database = "data/data/" + packagename + "/databases";
        String userString = cmd + "/XmlUser";
        String xmlsourceString = cmd + "/XmlSource";
        File sqlfile = new File(database);
        //File databaseFile=new File(database+"/");
        try {

            process = Runtime.getRuntime().exec("su");
            oStream = new DataOutputStream(process.getOutputStream());
            oStream.writeBytes(cmddata + "\n");
            oStream.writeBytes(cmddatadata + "\n");
            oStream.writeBytes(cmd + "\n");
            if (!sqlfile.exists()) {
                sqlfile.mkdirs();
            }
            oStream.writeBytes(cmd + "/databases" + "\n");
            //	 oStream.writeBytes(cmd+"/databases"+"/TTYCRecords.db"+"\n");
            oStream.writeBytes(userString + "\n");
            oStream.writeBytes(xmlsourceString + "\n");
            oStream.writeBytes("exit\n");
            oStream.flush();
            process.waitFor();

        } catch (Exception e) {
            // TODO: handle exception
        } finally {
            try {
                if (oStream != null) {
                    oStream.close();
                }
                process.destroy();
            } catch (Exception e) {
                // TODO: handle exception
            }
        }

    }


    private void findViews() {
        username = (EditText) findViewById(R.id.username);
        password = (EditText) findViewById(R.id.password);
        login = (Button) findViewById(R.id.login);
        register = (Button) findViewById(R.id.register);
        cancel = (Button) findViewById(R.id.cancel);
        login.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                String name = username.getText().toString();
                String pass = password.getText().toString();
                Log.i("TAG", name + "_" + pass);
                UserService uService = new UserService(LoginActivity.this);
                boolean flag = uService.login(name, pass);
                if (flag) {

                    Intent intent = new Intent(LoginActivity.this, QcardInfoActivity.class);
                    startActivity(intent);
                    Log.i("TAG", "登录成功");
                    Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_LONG).show();
                } else {
                    Log.i("TAG", "登录失败");
                    Toast.makeText(LoginActivity.this, "登录失败", Toast.LENGTH_LONG).show();
                }
            }
        });
        register.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                //Intent intent=new Intent(LoginActivity.this,RegisterActivity.class);
                //startActivity(intent);
            }
        });
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.login, menu);
        return true;
    }

}
